package org.nimi317.web_gis.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.nimi317.web_gis.dao.AreaWeatherMapper;
import org.nimi317.web_gis.entity.Area;
import org.nimi317.web_gis.entity.AreaWeather;
import org.nimi317.web_gis.service.IAreaWeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * <p>
 * 大气数据 服务实现类
 * </p>
 *
 * @author yh
 * @since 2024-03-10
 */
@Service
@Slf4j
public class AreaWeatherServiceImpl extends ServiceImpl<AreaWeatherMapper, AreaWeather> implements IAreaWeatherService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AreaWeatherMapper areaWeatherMapper;

    @Override
    @Async
    public void refreshWeather(Area s) {
        HttpRequest request = HttpUtil.createGet("http://www.nmc.cn/rest/weather?stationid=" + s.getCode());
        try (HttpResponse response = request.execute()) {
            Map o = (Map) objectMapper.readValue(response.body(), Map.class).get("data");
            Map real = (Map) o.get("real");
            Map weather = (Map) real.get("weather");
            Map wind = (Map) real.get("wind");
            LocalDateTime publishTime = LocalDateTime.parse(real.get("publish_time").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            if (publishTime.getMinute() != 0) {
                //整点 才进行储存
                return;
            }
            LambdaQueryWrapper<AreaWeather> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AreaWeather::getPublishTime, publishTime)
                    .eq(AreaWeather::getCityCode, s.getCityCode());
            Long count = areaWeatherMapper.selectCount(wrapper);
            if (count > 0) {
                return;
            }
            AreaWeather entity = new AreaWeather(s.getCityCode(), publishTime, (Double) weather.get("rain"), (Double) weather.get("temperature"), wind.get("direct").toString(), (Double) wind.get("degree"), (Double) weather.get("humidity"), wind.get("power").toString(), (Double) wind.get("speed"), weather.get("info").toString());
            areaWeatherMapper.insert(entity);
        } catch (Exception e) {
            log.error("天气信息入库失败:", e);
        }
    }
}
